<template>

  <div class="app-container">
    <el-container>
      <el-header>
        <el-form :inline="true" :model="searchForm">

          <el-form-item label="选择网站" class="mt-form-item-left">
            <el-select v-model="searchForm.selected_website" filterable clearable @change="handleSearch">
              <el-option label="所有" value="" />
              <el-option
                v-for="(item,index) in searchForm.websites"
                :key="index"
                :label="item.domain + '|' + item.message_count"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="选择状态" class="mt-form-item-left">
            <el-select v-model="searchForm.selected_status" filterable clearable>
              <el-option
                v-for="(item,index) in searchForm.dataStatus"
                :key="index"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>

          <el-form-item class="mt-form-item-search">
            <el-input
              v-model="kwInput"
              placeholder="搜索关键词"
              clearable
              :autosize="{ minRows: 4}"
              @keyup.native.enter="handleSearch"
            />
          </el-form-item>

          <el-form-item style="width:94px;">
            <el-checkbox v-model="searchForm.only_no_reply">只看未回复</el-checkbox>
          </el-form-item>
          <el-form-item style="width:94px;">
            <el-checkbox v-model="searchForm.marked">只看标记的</el-checkbox>
          </el-form-item>

          <el-form-item style="width:100px;">
            <el-button type="primary" style="float: right;" @click="handleSearch">搜索</el-button>
          </el-form-item>
        </el-form>
      </el-header>
      <el-container :style="styleObject">
        <el-aside width="475px">
          <el-col v-loading="messageLoading" :span="6" style="background: white" class="fixed">
            <div v-if="current_message.messages.length" style="text-align: center; margin: 10px;">
              <a
                v-if="current_message.id"
                :href="base_api + '/customer-thread/' + current_message.id"
                target="_blank"
                style="text-decoration: underline;color: #409EFF;"
              >消息链接</a>
              <el-button size="mini" type="success" :disabled="!current_message.id_customer" @click="showCustomer">
                查看顾客信息
              </el-button>
              <el-button size="mini" type="success" :disabled="!current_message.id_order" @click="showOrder">查看订单信息
              </el-button>
            </div>

            <timeline timeline-theme="lightblue" style="padding-top: 5px" size="mini">
              <timeline-title style="width: auto;display: block;word-wrap: break-word;">
                <a class="mt-href" :href="current_message.title | erpFilter" target="_blank">
                  {{ current_message.title }}</a></timeline-title>
              <timeline-item v-for="item in current_message.messages" :key="item.id" color="orange">
                <p>
                  <i class="el-icon-date">{{ item.date_upd.split('T')[0] }}</i>
                  <i class="el-icon-time">{{ item.date_upd.split('T')[1] }}</i>
                  <svg-icon v-if="item.id_employee" icon-class="admin" style="float: right" />
                </p>
                <p class="mt-message" v-html="item.message" />
                <a
                  v-if="item.file_name"
                  :href="item.file_name"
                  target="_blank"
                  class="mt-href"
                >Attachments</a>
                <span v-if="item.id_employee" style="color:red;float:right">By admin</span>
              </timeline-item>
            </timeline>
            <el-button
              v-if="current_message.messages.length"
              style="float: right;margin: 10px"
              type="success"
              size="mini"
              :disabled="thread_status"
              @click="handleReply"
            >
              回复
            </el-button>
          </el-col>
        </el-aside>
        <el-container>
          <el-main>
            <div :gutter="10">
              <el-col v-loading="listLoading">
                <div style="display: flex;flex-direction: row-reverse;margin: 5px">
                  <el-button
                    size="mini"
                    type="success"
                    :disabled="!checkedIds.length"
                    @click="handleReply('batch')"
                  >批量回复
                  </el-button>
                  <el-button size="mini" type="primary" style="margin-right: 10px" @click="handleSelectAll">全选/取消
                  </el-button>
                  <div v-loading="tagLoading" style="text-align: center">
                    <el-tag v-for="tag in tags" :key="tag.id" closable @close="handleClose(tag.id)">{{ tag.name }}
                    </el-tag>
                    <el-input
                      v-if="inputVisible"
                      ref="saveTagInput"
                      v-model="inputValue"
                      class="input-new-tag"
                      size="small"
                      @keyup.enter.native="handleInputConfirm"
                      @blur="handleInputConfirm"
                    />
                    <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
                  </div>
                </div>
                <el-card
                  v-for="item in data"
                  :key="item.id"
                  :body-style="{ padding: '0px' }"
                  shadow="hover"
                  style="margin-bottom: 20px"
                >
                  <div slot="header" class="clearfix">
                    <el-checkbox v-model="item.checked" @change="handleSelectSingle" />

                    <a class="mt-href" :href="item.email | erpFilter" target="_blank">{{ item.email }}</a>
                    <span><el-tag
                      type="danger"
                      style="margin-left: 10px"
                      size="mini"
                    >{{ item.last_date }}</el-tag></span>
                    <el-button
                      v-if="item.marked === false"
                      style="float: right; padding: 3px 0;color: red"
                      type="text"
                      @click="handleMessageTaggle(item)"
                    >
                      <el-icon class="el-icon-star-off" />
                      稍后处理
                    </el-button>
                    <el-button
                      v-else="item.marked === true"
                      style="float: right; padding: 3px 0;color: green"
                      type="text"
                      @click="handleMessageTaggle(item)"
                    >
                      <el-icon class="el-icon-star-on" />
                      取消标记
                    </el-button>

                  </div>
                  <span style="margin-left: 10px;color: #909399;margin-right: 10px; font-size: xx-small">来自:{{ item.website__domain }}</span>
                  <p style="padding: 14px" v-html="item.message" />
                  <a
                    v-if="item.file_name"
                    style="padding: 14px"
                    :href="item.file_name"
                    target="_blank"
                    class="mt-href"
                  >Attachments</a>
                  <p v-if="item.translate_query.length" style="padding: 14px;color:blue" v-html="item.translate_query" />
                  <a
                    v-if="item.file_name"
                    :href="item.file_name"
                    target="_blank"
                    style="text-decoration: underline;color: #409EFF;"
                  >Attachments</a>
                  <div class="clearfix" style="margin-left: 10px;height: 36px">
                    <el-tag v-for="tag in item.tags" v-if="item.tags.length" :key="tag" type="danger" style="margin-left: 5px;">{{ tag }}
                    </el-tag>
                    <span
                      :class="[item.id_employee ? red : blue]"
                      style="float:right;margin-right: 20px;top: 50%;
            transform: translateY(50%);"
                    >{{ item.id_employee? '来自站长': '来自客户' }}</span>
                    <!--<span class="red" style="float:right;margin-right: 20px;top: 50%;-->
                    <!--transform: translateY(50%);" @mouseenter.native="handleTranslate(item)">翻译</span>-->
                    <el-button
                      style="float:right;margin-right: 20px;top: 50%;-->
            <!--transform: translateY(50%);"
                      plain
                      size="mini"
                      @click="handleTranslate(item)"
                      @mouseenter.native="handleTranslate(item)"
                    >
                      翻译
                    </el-button>
                  </div>
                  <div style="padding: 14px;">
                    <div class="bottom clearfix">

                      <el-button
                        style="float: left;"
                        type="success"
                        size="mini"
                        :disabled="thread_status"
                        @click="handleQuickReply(item)"
                      >快速回复
                      </el-button>
                      <el-badge
                        v-if="item.message__count > 1"
                        style="float: left;margin-left: 5px"
                        :value="item.message__count"
                        class="item"
                      >
                        <el-button
                          plain
                          size="mini"
                          @click="showThread(item)"
                          @mouseenter.native="showThread(item)"
                        >
                          查看对话过程
                        </el-button>
                      </el-badge>
                      <el-button
                        v-else
                        plain
                        size="mini"
                        @click="showThread(item)"
                        @mouseenter.native="showThread(item)"
                      >
                        查看对话过程
                      </el-button>
                      <div style="float: right">
                        <i class="el-icon-date">{{ item.last_date_upd.split('T')[0] }}</i>
                        <i class="el-icon-time">{{ item.last_date_upd.split('T')[1] }}</i>
                      </div>

                    </div>
                  </div>
                </el-card>

              </el-col>

            </div>
          </el-main>
          <el-footer height="30px" style="margin-bottom: 20px">
            <el-pagination
              v-if="data.length"
              background
              class="mt-pagination"
              :current-page="page"
              :page-sizes="[10,20,50,100]"
              :page-size="pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handlePageChange"
            />
          </el-footer>
        </el-container>
      </el-container>

    </el-container>

    <el-dialog
      v-loading="dialogLoading"
      :title="batch? '回复消息(批量)' : '回复消息(单个)'"
      :visible.sync="dialogVisible"
      width="50%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >

      <el-form :model="temp" label-width="80px" size="mini">
        <el-form-item label="模板">
          <el-select
            v-model="temp.selected_template"
            placeholder="请选择"
            filterable
            clearable
            size="mini"
            @change="handleSelectTemplate"
          >
            <el-option
              v-for="(item, index) in templates"
              :key="index"
              :label="item.name"
              :value="item.text"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="消息">
          <el-input v-model="temp.text" placeholder="回复内容" type="textarea" :autosize="{ minRows: 6 }" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="send">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { Timeline, TimelineItem, TimelineTitle } from 'vue-cute-timeline'
import { Get as GetTemplates } from '@/api/psmsg/replyTemplate'
import { Get as GetWebsite } from '@/api/erp/elicink/website'
import { Get as GetTag, Post as PostTag, Delete as DeleteTag } from '@/api/psmsg/tag'
import { dt, sendMsg, showMsg, showOrderInfo, showCustomerInfo, message_taggle } from '@/api/psmsg/message'
import { Translate } from '@/api/baidu'
import qs from 'qs'

export default {
  components: {
    Timeline,
    TimelineItem,
    TimelineTitle
  },
  filters: {
    colorFilter(v) {
      return v ? `"color":"green"` : `"color":"red"`
    },
    erpFilter(v) {
      return 'http://erp.elicink.com:19870/ps/order?wid=&status=&sort=id_desc&pagesize=50&page=0&isWeb=on&searchKey=' + encodeURI(v)
    }
  },
  data() {
    return {
      styleObject: {
        height: document.documentElement.clientHeight - 150 + 'px'
      },
      base_api: '',
      tags: [],
      tagLoading: false,
      inputVisible: false,
      inputValue: '',

      listLoading: false,
      messageLoading: false,
      searchForm: {
        selected_website: '',
        websites: [],
        dataStatus: ['open', 'closed'],
        selected_status: 'open',
        only_no_reply: true,
        marked: false
      },
      // 输入
      kwInput: '',
      // pagination
      pagesize: 10,
      page: 1,
      total: 0,

      templates: [],
      dialogLoading: false,
      dialogVisible: false,
      temp: {
        selected_template: null,
        text: ''
      },

      data: [],
      checkedIds: [],

      thread_status: false,
      current_message: {
        id_customer: null,
        id: null,
        id_order: null,
        title: '',
        messages: []
      },
      batch: false,

      notreply: 'notreply',
      hasreply: 'hasreply',

      red: 'm-red',
      blue: 'm-blue'
    }
  },
  created() {
    this.getTags()
    GetWebsite(null, qs.stringify({
      message_count: 1
    })).then(response => {
      this.searchForm.websites = response.data.data
      this.searchForm.selected_website = this.searchForm.websites[0].id
      this.getList()
    })

    const m = window.location.href.split('/')
    m.splice(window.location.href.split('/').length - 1, 1)
    this.base_api = m.join('/')
  },
  mounted() {
    const that = this
    window.onresize = () => {
      return (() => {
        that.styleObject =
            {
              height: document.documentElement.clientHeight - 150 + 'px'
            }
      })()
    }
  },
  methods: {
    handleTranslate(item) {
      if (item.translate_query.length) {
        return
      }
      Translate({ q: item.message }).then((response) => {
        for (var x in response.data.trans_result) {
          item.translate_query = item.translate_query + ' ' + response.data.trans_result[x].dst
        }
      })
    },
    getTags() {
      this.tagLoading = true
      GetTag().then(response => {
        this.tags = response.data.data
        this.tagLoading = false
      }).catch(e => {
        this.tagLoading = false
      })
    },
    scrollTop() {
      window.scrollTo(0, 0)
    },
    handleMessageTaggle(item) {
      message_taggle({ id: item.message_id }).then(response => {
        item.marked = !item.marked
      }).catch(e => {
        this.notify('保存失败')
      })
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    getList() {
      this.listLoading = true
      dt({
        kw: this.kwInput,
        pagesize: this.pagesize,
        page: this.page,
        website_id: this.searchForm.selected_website,
        marked: this.searchForm.marked,
        status: this.searchForm.selected_status,
        only_no_reply: this.searchForm.only_no_reply
      }).then(response => {
        this.checkedIds = []
        this.data = response.data.data.map(v => {
          this.$set(v, 'checked', false)
          this.$set(v, 'translate_query', '')
          return v
        })
        this.total = response.data.total
        this.listLoading = false
        this.scrollTop()
      }).catch(e => {
        this.listLoading = false
      })
    },
    showThread(v, func) {
      if (v.id === this.current_message.id) {
        if (func) func()
        return
      }
      this.messageLoading = true
      showMsg(v.id).then(response => {
        this.current_message.messages = response.data
        this.current_message.title = v.email
        this.current_message.id = response.id
        this.current_message.id_customer = response.id_customer
        this.current_message.id_order = response.id_order
        this.current_message.website_id = response.website_id
        this.thread_status = response.thread_status

        this.messageLoading = false
        if (func) func()
      }).catch(e => {
        this.messageLoading = false
      })
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    handleSearch() {
      this.page = 1
      this.getList()
    },
    handleReply(bool_batch) {
      this.resetTemp()
      this.dialogLoading = true
      this.dialogVisible = true
      if (bool_batch) {
        this.batch = true
        // 批量回复，清空左侧消息，修改配置
        this.current_message = {
          id_customer: null,
          id: null,
          id_order: null,
          title: '',
          messages: []
        }
        this.current_message.id = this.checkedIds
      } else {
        this.batch = false
      }
      GetTemplates().then(response => {
        this.templates = response.data.data
        this.dialogLoading = false
      }).catch(e => {
        this.dialogLoading = false
      })
    },
    handleSelectTemplate(v) {
      this.temp.text = v
    },
    send() {
      this.dialogLoading = true
      sendMsg({
        id: this.current_message.id,
        message: this.temp.text
      }).then(response => {
        this.$notify({
          title: '成功',
          message: '发送消息成功',
          type: 'success',
          duration: 20000
        })
        this.dialogVisible = false
        this.dialogLoading = false
        this.messageLoading = false
        this.getList()
      }).catch(e => {
        this.dialogLoading = false
      })
    },
    resetTemp() {
      this.temp = {
        selected_template: null,
        text: 'Dear Customer:\nOK\nCustomer Service',
        id_customer: null,
        id_order: null,
        messages: []
      }
    },
    showCustomer() {
      this.messageLoading = true
      showCustomerInfo({
        id: this.current_message.id,
        id_customer: this.current_message.id_customer
      }).then(response => {
        this.messageLoading = false
        this.$alert(this.liFilter(response.data), 'Customer Info', {
          dangerouslyUseHTMLString: true
        })
      }).catch(e => {
        this.messageLoading = false
      })
    },
    showOrder() {
      this.messageLoading = true
      showOrderInfo({
        id: this.current_message.id,
        id_order: this.current_message.id_order,
        website_id: this.current_message.website_id
      }).then(response => {
        this.messageLoading = false
        this.$alert(this.liFilter(response.data), 'Order Info', {
          dangerouslyUseHTMLString: true
        }).catch(e => {
          this.messageLoading = false
        })
      })
    },
    liFilter(v) {
      const href_words = ['order_id', 'order_reference', 'email']
      return '<table border="1">' + v.map(k => {
        if (href_words.includes(k[0])) {
          const url = 'http://erp.elicink.com:19870/ps/order?wid=&status=&sort=id_desc&pagesize=50&page=0&isWeb=on&searchKey=' + encodeURI(k[1])
          const link = '<a style="text-decoration: underline;color: #409EFF;" href=' + url + ' target="_blank">' + k[1] + '</a>'
          return '<tr><th>' + k[0] + '</th><th>' + link + '</th></tr>'
        } else {
          return '<tr><th>' + k[0] + '</th><th>' + k[1] + '</th></tr>'
        }
      }
      ).join('') + '</table>'
    },

    handleClose(v) {
      this.tagLoading = true
      DeleteTag(v).then(response => {
        this.listLoading = false
        this.getTags()
      }).catch(e => {
        this.listLoading = false
        this.getTags()
      })
    },

    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        PostTag({ name: inputValue }).then(response => {
          this.getTags()
          this.inputVisible = false
          this.inputValue = ''
        })
      }
    },
    handleQuickReply(item) {
      const promise = new Promise(function(resolve, reject) {
        resolve()
      })
      promise.then(this.showThread(item, this.handleReply))
    },
    handleSelectAll() {
      const _total = this.data.length
      const _checked_length = this.data.filter(m => m.checked).length
      if (_checked_length) {
        if (_checked_length < _total) {
          this.checkedIds = this.data.map(m => {
            m.checked = true
          })
        } else {
          this.data.map(m => {
            m.checked = false
          })
          this.checkedIds = []
        }
      } else {
        this.data.map(m => {
          m.checked = true
        })
        this.checkedIds = this.data.map(m => m.id)
      }
    },
    handleSelectSingle(v) {
      this.checkedIds = this.data.filter(m => m.checked).map(m => m.id)
    }
  }
}
</script>

<style scoped>
  .app-container >>> em {
    color: red;
  }

  .mt-message {
    padding: 0 0 0 10px;
    border-left: 2px solid #ccc;

    word-break: normal;
    width: auto;
    display: block;
    white-space: pre-wrap;
    word-wrap: break-word;
  }

  .clearfix:before,
  .clearfix:after {
    display: block;
    content: '';
    clear: both;
    height: 0;
  }

  .mt-pagination {
    float: right;
    margin-top: 5px;
  }

  .top {
    margin: 20px;
  }

  .top >>> .el-tag + .el-tag {
    margin-left: 10px;
  }

  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }

  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }

  .hasreply {
    display: inline-block;
    width: 100px;
    background-color: #67C23A;
    text-align: center;
    color: black;
  }

  .notreply {
    display: inline-block;
    width: 100px;
    background-color: #F56C6C;
    text-align: center;
    color: black;
  }

  .fixed {
    position: fixed;
    top: 140px;
    overflow-y: scroll;
    height: calc(100% - 264px);
  }

  .fixed::-webkit-scrollbar { /*滚动条整体样式*/
    width: 10px; /*高宽分别对应横竖滚动条的尺寸*/
    height: 1px;
  }

  .fixed::-webkit-scrollbar-thumb { /*滚动条里面小方块*/
    border-radius: 10px;
    background-color: #F90;
    background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .2) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .2) 50%, rgba(255, 255, 255, .2) 75%, transparent 75%, transparent);
  }

  .fixed::-webkit-scrollbar-track { /*滚动条里面轨道*/
    -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    /*border-radius: 10px;*/
    background: #EDEDED;
  }

  .mt-href {
    text-decoration: underline;
    color: #409EFF;
  }

  .m-red {
    color: red;
  }

  .m-blue {
    color: #409EFF;
  }

  .mt-form-item-left {
    width: 26%;
    margin-right: 0;
  }

  .el-form-item {
    margin-bottom: 1px;
  }

  .mt-form-item-left >>> .el-form-item__content {
    width: calc(100% - 80px);
  }

  .mt-form-item-left >>> .el-select {
    width: 100%;
  }

  div.is-hover-shadow:hover {
    border-color: red;
  }

  .mt-form-item-search >>> .el-form-item__content {
    width: 100%;
  }
</style>
